const webpack = require('webpack');
const { AngularWebpackPlugin } = require('@ngtools/webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');

const isProd = process.env.NODE_ENV === 'production'; // 是否生产环境

module.exports = {
  entry: {
    main: path.join(__dirname, '../src/main.ts'),
  },
  output: {
    path: path.join(__dirname, '../dist'),
    filename: isProd ? '[name].[contenthash].js' : '[name].js',
    clean: true,
  },
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [
      path.resolve(__dirname, '../src'),
      path.resolve(__dirname, '../node_modules'),
    ],
    alias: {
      '@': path.resolve(__dirname, '../src'),
      '@app': path.resolve(__dirname, '../src/app'),
      '@pages': path.resolve(__dirname, '../src/pages'),
    },
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: '@ngtools/webpack',
        exclude: [path.resolve(__dirname, '../node_modules')],
      },
      {
        test: /\.html$/,
        use: 'html-loader',
        exclude: [path.resolve(__dirname, '../node_modules')],
      },
      {
        test: /\.less$/,
        use: ['raw-loader', 'less-loader'],
        exclude: [path.resolve(__dirname, '../node_modules')],
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      PUBLIC_URL: JSON.stringify(path.resolve(__dirname, '../public')),
      __DEV__: JSON.stringify(process.env.NODE_ENV),
    }),
    new AngularWebpackPlugin({
      tsconfig: path.resolve(__dirname, '../tsconfig.json'),
      jitMode: true, // 开启 AOT
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '../src/index.html'),
      filename: 'index.html',
      favicon: path.resolve(__dirname, '../public/favicon.ico'),
      inject: true,
    }),
  ],
};
